package br.com.management.mentor.view.users;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.configuration.Configuration;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import br.com.management.mentor.app.Config;
import br.com.management.mentor.app.components.FilesResourceLocator;
import br.com.management.mentor.app.exceptions.IconImgIOException;
import br.com.management.mentor.app.exceptions.IconImgNotFoundException;
import br.com.management.mentor.controller.auth.UserController;
import br.com.management.mentor.model.entities.auth.User;
import br.com.management.mentor.model.repositories.UsersRepository;
import br.com.management.mentor.util.EclipseBug154341Hack;
import br.com.management.mentor.view.core.View;

@Component
public class List extends View {

	private Composite parent;

	private int maxResults = 10;

	private int firstResult = 0;

	@Autowired
	private Configuration configuration;

	@Autowired
	private UsersRepository usersRepository;

	@Autowired
	private FilesResourceLocator fileResourceLocator;

	@Autowired
	private ApplicationContext context;
	
	@Autowired
	private UserController userController;

	@Override
	public void build( Composite parent ) {
		this.parent = parent;
		
		final Table usersTable = new Table( parent , SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.CHECK );
		usersTable.setLinesVisible( true );

		TableColumn optionsColumn = new TableColumn( usersTable , SWT.CENTER );
		optionsColumn.setText( "Opções" );
		optionsColumn.setToolTipText( "Ações que podem ser realizadas no usuário selecionado" );
		optionsColumn.setResizable( true );
		optionsColumn.setWidth( 200 );

		TableColumn usernameColumn = new TableColumn( usersTable , SWT.LEFT );
		usernameColumn.setText( "Usuário" );
		usernameColumn.setToolTipText( "Login do usuário" );
		usernameColumn.setResizable( true );

		TableColumn creationDateColumn = new TableColumn( usersTable , SWT.CENTER );
		creationDateColumn.setText( "Data de Criação" );
		creationDateColumn.setToolTipText( "Data que o usuário foi cadastrado" );
		usernameColumn.setResizable( true );

		usersTable.setSortColumn( usernameColumn );
		usersTable.setHeaderVisible( true );
		usersTable.setSortDirection( SWT.DOWN );

		optionsColumn.addListener( SWT.Resize , new Listener() {
			@Override
			public void handleEvent( Event event ) {
				int min = 45;
				EclipseBug154341Hack.setItemHeight( usersTable , min );
			}
		} );

		usersTable.addListener( SWT.MeasureItem , new Listener() {
			public void handleEvent( Event event ) {
				TableItem item = (TableItem) event.item;
				String text = item.getText( event.index );
				Point size = event.gc.textExtent( text );
				event.height = Math.max( event.height , size.y );
			}
		} );

		usernameColumn.addSelectionListener( new SelectionListener() {

			@Override
			public void widgetSelected( SelectionEvent e ) {
				// TODO: implementar
				/* Reset to known state: 'down' on column 0. */
				// table1.setSortDirection (SWT.DOWN);
				// for (int i = 0; i < columns.length; i++) {
				// TableColumn column = columns[i];
				// if (i == 0) table1.setSortColumn(column);
				// SelectionListener listener = new SelectionAdapter() {
				// @Override
				// public void widgetSelected(SelectionEvent e) {
				// int sortDirection = SWT.DOWN;
				// if (e.widget == table1.getSortColumn()) {
				// /* If the sort column hasn't changed, cycle down -> up ->
				// none. */
				// switch (table1.getSortDirection ()) {
				// case SWT.DOWN: sortDirection = SWT.UP; break;
				// case SWT.UP: sortDirection = SWT.NONE; break;
				// }
				// } else {
				// table1.setSortColumn((TableColumn)e.widget);
				// }
				// table1.setSortDirection (sortDirection);
				// }
				// };
				// column.addSelectionListener(listener);
				//					column.setData("SortListener", listener);	//$NON-NLS-1$
				// }
			}

			@Override
			public void widgetDefaultSelected( SelectionEvent e ) { }

		} );
		// TODO: implementar paginação
		java.util.List<User> users = usersRepository.getActives( firstResult , maxResults );

		SimpleDateFormat sdf = new SimpleDateFormat( "dd/MM/yyyy" );

		String editOption = configuration.getString( Config.EDIT_ICON.name() );

		String imgURL = fileResourceLocator.getIconImgURL( editOption );
		Resource resource = context.getResource( imgURL );

		if ( !resource.exists() )
			throw new IconImgNotFoundException( new Object[] { editOption } );

		if ( !CollectionUtils.isEmpty( users ) ) {
			for ( User user : users ) {
				TableItem item = new TableItem( usersTable , SWT.NONE );

				File file = null;
				try {
					file = resource.getFile();
				} catch ( IOException e ) {
					throw new IconImgIOException( new Object[] { editOption } );
				}

				Image image = new Image( parent.getDisplay() , file.getAbsolutePath() );

				Button editBtn = new Button( usersTable , SWT.PUSH );
				editBtn.setImage( image );
				editBtn.setSize( 40 , 40 );
				editBtn.setToolTipText( "Editar" );

				TableEditor editor = new TableEditor( usersTable );
				editor.minimumWidth = editBtn.getSize().x;
				editor.horizontalAlignment = SWT.CENTER;
				editor.setEditor( editBtn , item , 0 );

				item.setText( 1 , user.getUsername() );
				item.setText( 2 , sdf.format( user.getCreationDate() ) );
				item.setData( user );
				
			}
		}
		
		Button deleteBtn = new Button( parent , SWT.PUSH );
		deleteBtn.setText( "Remover" );
		deleteBtn.addSelectionListener( new SelectionListener() {
			
			@Override
			public void widgetSelected( SelectionEvent e ) {
				
				for ( TableItem item : usersTable.getItems() ) {
					if ( item.getChecked() ) {
						userController.delete( (User) item.getData() );
					}
				}
			}
			
			@Override
			public void widgetDefaultSelected( SelectionEvent e ) { }
		} );
		
		packColumns( usersTable );
	}

	@Override
	public Shell getParent() {
		return parent.getShell();
	}

	private void packColumns( Table table ) {
		for ( TableColumn tableColumn : table.getColumns() )
			tableColumn.pack();
	}
}